import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProConfigProvider, ProFormText } from '@ant-design/pro-components';
import { message, theme } from 'antd';
import store from 'storejs';
import './index.less';
import { useEffect, useRef } from 'react';
import { isLocal, isSuccess, notify, wait } from '@/utils';
import { loginApi } from '@/api';
import { useSetAtom } from 'jotai';
import { userStore } from '@/stores';

export default function Login() {
  const { token } = theme.useToken();
  const setUserStore = useSetAtom(userStore);
  const formRef: any = useRef('');

  useEffect(() => {
    if (!isLocal()) return;
    formRef?.current?.setFieldsValue({
      username: 'kaifa',
      password: '123456',
    });
  }, []);

  // 登录
  async function submitApi(values: any) {
    const { username, password } = values;
    const params = { name: username, password };
    const res: any = await loginApi(params);
    if (isSuccess(res) && canUse(res)) {
      setUserStore(res?.data?.userInfo);
      store.set('token', res?.data?.token);
      window.location.href = `/home?contract=BTC_USDT`;
    }
  }

  // 检测账号是否可用
  function canUse(res: any) {
    if (!res?.data?.userInfo?.is_active) {
      message.error('账户已被禁用，请联系管理员');
      return false;
    }
    if (!res?.data?.userInfo?.zhima) {
      message.error('此芝麻账户没数据，请联系管理员');
      return false;
    }
    if (!res?.data?.userInfo?.zhima?.is_active) {
      message.error('芝麻账户已被禁用，请联系管理员');
      return false;
    }
    return true;
  }

  return (
    <div className="loginpage">
      <ProConfigProvider hashed={false}>
        <div style={{ backgroundColor: token.colorBgContainer }}>
          <LoginForm
            // logo="https://github.githubassets.com/favicons/favicon.png"
            formRef={formRef}
            title="交易平台"
            subTitle={'欢迎登录'}
            onFinish={async (values) => submitApi(values)}
          >
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixI con'} />,
              }}
              placeholder={'用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </LoginForm>
        </div>
      </ProConfigProvider>
    </div>
  );
}
